package com.hj.dapp.business.unit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hj.dapp.business.unit.mapper.UnitMapper;
import com.hj.dapp.business.unit.model.Unit;
import com.hj.dapp.business.unit.service.UnitService;
import com.hj.dapp.common.request.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2024/1/22
 */
@Service
public class UnitServiceImpl implements UnitService {

    @Autowired
    private UnitMapper unitMapper;

    @Override
    public Unit get(Long id) {
        return unitMapper.selectById(id);
    }

    @Override
    public IPage<Unit> page(PageRequest<Unit> request) {
        Page<Unit> page = new Page<>();
        page.setSize(request.getSize());
        page.setCurrent(request.getCurrent());
        QueryWrapper<Unit> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(request.getQuery())) {
            if (!ObjectUtils.isEmpty(request.getQuery().getName())) {
                queryWrapper.like("name", request.getQuery().getName());
            }
        }
        return unitMapper.selectPage(page, queryWrapper);
    }

    @Override
    public void edit(Unit unit, Principal principal) {
        unit.setLastUpdateBy(principal.getName());
        unit.setLastUpdateTime(LocalDateTime.now());
        unitMapper.updateById(unit);
    }

    @Override
    public void save(Unit unit, Principal principal) {
        unit.setCreateTime(LocalDateTime.now());
        unit.setCreateBy(principal.getName());
        unitMapper.insert(unit);
    }

    @Override
    public void delete(Long id) {
        unitMapper.deleteById(id);
    }

    @Override
    public List<Unit> list() {
        return unitMapper.selectList(null);
    }

}
